stop on stopping <%= app %>-<%= process.name %>

respawn
respawn limit 10 5
kill timeout 20

instance $INSTANCE

env PORT=<%= port %>
<% engine.environment.each_pair do |var,value| %>
env <%= var.upcase %>=<%= value %>
<% end %>

script
  export name="<%= app %>-<%=process.name%>-$INSTANCE"

  # This little dance pipes output into logger with three
  # goals in mind:
  #  - Keep the process as a direct child of init (so upstart
  #    doesn't get confused).
  #  - Make sure logger isn't a child of the process (so it
  #    doesn't get confused).
  #  - Don't leave cruft sitting around in the filesystem.

  # See `man 7 fifo` and `man 7 pipe` for more info.
  mkdir -p <%= log_root %>
  stdout_fifo="<%= log_root %>/$name-stdout-log.fifo"
  stderr_fifo="<%= log_root %>/$name-stderr-log.fifo"
  rm -f $stdout_fifo
  rm -f $stderr_fifo
  mkfifo $stdout_fifo
  mkfifo $stderr_fifo

  # Capture our pid so we can pass it to logger to record 
  # the pid of the actual job and not the pid of the logger
  # background process.
  job_pid=$$

  # Start logger reading from the fifos, in the background.
  # The parens cause the logger process to be reparented to
  # init, rather than remaining a child of the current proc.
  #
  # `setsid` will cause loggers to be in a different session
  # and process group. If we let the loggers be in the same
  # process group as the main process, they would be killed
  # by upstart together with the main process, and all output
  # would be suppressed during termination.
  ( exec setsid logger -p local0.notice -t "$name[$job_pid]" <$stdout_fifo & )
  ( exec setsid logger -p local0.err    -t "$name[$job_pid]" <$stderr_fifo & )

  # Redirect the current shell's output to the fifos. Now that
  # we have open fds for those fifos, we don't need the file
  # system entries any more...
  exec >$stdout_fifo 2>$stderr_fifo

  # ...so we'll remove them.
  rm $stdout_fifo
  rm $stderr_fifo

  # Run the service in the usual way. Our output is already
  # going to the fifos; that won't change when the new
  # program executes.

  exec sudo -u <%= user %> PORT=$(( $PORT + $INSTANCE - 1 )) <%= process.name.upcase.gsub('-', '_') %>_INSTANCE=$INSTANCE<% engine.environment.each_pair do |var,value| %> <%= var.upcase %>=<%= value %><% end %> -i <%= process.command %>
end script
